import {
  getNewCartGoods,
  mergeLocalCart,
  findCartList,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from "@/api/cart"

export default {
  namespaced: true,
  state() {
    return {
      List: []
    }
  },
  mutations: {
    // 本地：id skuId name picture price nowPrice count attrsText selected stock isEffective
    insertCart(state, goods) {
      // 同商品只增加商品数量
      const sameIndex = state.List.findIndex(item => item.skuId === goods.skuId)
      if (sameIndex > -1) {
        goods.count = state.List[sameIndex].count + goods.count
        state.List.splice(sameIndex, 1)
      }
      state.List.unshift(goods)
    },
    // 修改购物车商品属性
    updateCart(state, goods) {
      // 保证数据的完整性 并且需要包含skuId
      const updateGoods = state.List.find(item => item.skuId == goods.skuId)
      for (const key in goods) {
        // 布尔类型 false 值需要使用
        if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
          updateGoods[key] = goods[key]
        }
      }
    },
    // 删除购物车中的指定商品
    deleteCart(state, skuId) {
      const index = state.List.findIndex(item => item.skuId == skuId)
      state.List.splice(index, 1)
    },
    // 设置购物车列表
    setCartList(state, list) {
      state.List = list
    }
  },
  actions: {
    insertCart(context, goods) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //加入到后台后需要重新获取新得购物车信息
          insertCart(goods).then(() => {
            return findCartList()
          }).then((data) => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          //本地 - 直接存储购物车信息到本地localStorage
          context.commit('insertCart', goods)
          resolve()
        }
      })
    },
    deleteCart(context, skuId) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //以登陆 - 删除后台,重新获取
          deleteCart([skuId]).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          //未登录
          context.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 批量删除商品
    batchDeleteCart(context, isClear) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 得到需要删除的商品列表（失效，选中）的skuId集合
          const skuIds = context.getters[isClear ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCart(skuIds).then(() => {
            return findCartList()
          }).then((data) => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          context.getters[isClear ? "invalidList" : "selectedList"].forEach(item => {
            context.commit('deleteCart', item.skuId)
          })
          resolve()
        }
      })
    },
    /**
     * 更新商品信息 (状态,数量)
     * @param {*} context 
     * @param {Object} goods skuId,属性
     * @returns 
     */
    updateCart(context, goods) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //以登陆
          updateCart(goods).then(() => {
            return findCartList()
          }).then((data) => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          context.commit('updateCart', goods)
          resolve()
        }
      })
    },
    // 获取首页购物车有效商品列表
    findCartList(context) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //登录后获取购物车信息
          findCartList().then(data => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          //本地
          // Promise.all() 可以并列发送多个请求，等所有请求成功，调用then
          // 传参事promise数组
          const promiseArr = context.state.List.map(item => getNewCartGoods(item.skuId))
          Promise.all(promiseArr).then(dataList => {
            dataList.forEach((item, i) => {
              context.commit('updateCart', {
                //请求的id和列表中的Id是相同的
                skuId: context.state.List[i].skuId,
                ...item.result
              })
            })
            resolve()
          })
        }
      })
    },
    // 全选按钮操作
    checkedAllGoods(context, selected) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //得到每个有效商品skuId
          const ids = context.getters.validList.map(item => item.skuId)
          checkAllCart({
            selected,
            ids
          }).then(() => {
            return findCartList()
          }).then((data) => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          context.state.List.forEach(e => {
            context.commit('updateCart', {
              selected,
              skuId: e.skuId
            })
          })
          resolve()
        }
      })
    },
    updateCartSku(context, {
      oldSkuId,
      newSku
    }) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          //以登陆
          // 1. 获取原先商品的数量
          // 2. 删除原先商品
          // 3. 获取修改的skuId 和 原先商品数量 做一个加入购物车操作
          // 4. 更新列表
          const oldGoods = context.state.List.find(item => item.skuId === oldSkuId)
          deleteCart([oldSkuId]).then(() => {
            return insertCart({
              skuId: newSku.skuId,
              count: oldGoods.count
            })
          }).then(() => {
            return findCartList()
          }).then((data) => {
            context.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 但你修改了sku的时候其实skuId需要更改，相当于把原来的信息移出，创建一条新的商品信息。
          // 1. 获取旧的商品信息
          const oldGoods = context.state.List.find(item => item.skuId === oldSkuId)
          // 2. 删除旧的商品
          context.commit('deleteCart', oldSkuId)
          // 3. 合并一条新的商品信息
          const {
            skuId,
            price: nowPrice,
            inventory: stock,
            specsText: attrsText
          } = newSku
          const newGoods = {
            ...oldGoods,
            skuId,
            nowPrice,
            stock,
            attrsText
          }
          // 4. 去插入新得商品
          context.commit('insertCart', newGoods)
          resolve()
        }
      })
    },
    // 每次登录后都向服务器合并本地购物车数据
    async mergeLocalCart(context) {
      if (!context.rootState.user.profile.token) return
      //取出本地购物车数据
      const cartList = context.getters.validList.map(item => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      // 向服务器合并数据, 服务器存储
      await mergeLocalCart(cartList)

      //清空本地购物车列表
      context.commit('setCartList', [])
    }
  },
  getters: {
    // 购物车有效商品列表
    validList(state) {
      return state.List.filter(e => e.isEffective && e.stock > 0)
    },
    // 有效商品总件数
    validTotal(state, getters) {
      return getters.validList.reduce((total, c) => total += c.count, 0)
    },
    // 有效商品总金额
    validAmount(state, getters) {
      return getters.validList.reduce((total, c) => total += c.nowPrice * 100 * c.count, 0) / 100
    },
    // 选中商品列表
    selectedList(state, getters) {
      return getters.validList.filter(e => e.selected)
    },
    // 选中商品件数
    selectedTotal(state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount(state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100
    },
    // 是否全选
    validIsCheckAll(state, getters) {
      return getters.validList.length !== 0 && getters.validList.length === getters.selectedList.length
    },
    // 无效商品列表
    invalidList(state) {
      return state.List.filter(item => !(item.stock > 0 && item.isEffective))
    }
  }
}